package com.roger.homecenterscreen.ui.components

import androidx.compose.animation.core.*
import androidx.compose.foundation.Canvas
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.draw.scale
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.StrokeCap
import androidx.compose.ui.graphics.drawscope.DrawScope
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.roger.homecenterscreen.voice.VoiceState
import com.roger.homecenterscreen.voice.SynthesisState
import kotlin.math.sin

/**
 * 语音状态指示器
 */
@Composable
fun VoiceIndicator(
    voiceState: VoiceState,
    synthesisState: SynthesisState,
    recognitionResult: String,
    modifier: Modifier = Modifier
) {
    Column(
        modifier = modifier
            .background(
                color = Color.Black.copy(alpha = 0.7f),
                shape = RoundedCornerShape(16.dp)
            )
            .padding(16.dp),
        horizontalAlignment = Alignment.CenterHorizontally
    ) {
        // 状态指示器
        VoiceStatusIndicator(
            voiceState = voiceState,
            synthesisState = synthesisState
        )
        
        Spacer(modifier = Modifier.height(12.dp))
        
        // 状态文字
        Text(
            text = getStateText(voiceState, synthesisState),
            color = Color.White,
            fontSize = 14.sp,
            fontWeight = FontWeight.Medium,
            textAlign = TextAlign.Center
        )
        
        // 识别结果
        if (recognitionResult.isNotEmpty()) {
            Spacer(modifier = Modifier.height(8.dp))
            Text(
                text = "\"$recognitionResult\"",
                color = Color.White.copy(alpha = 0.9f),
                fontSize = 12.sp,
                textAlign = TextAlign.Center,
                modifier = Modifier
                    .background(
                        color = Color.White.copy(alpha = 0.1f),
                        shape = RoundedCornerShape(8.dp)
                    )
                    .padding(8.dp)
            )
        }
    }
}

/**
 * 语音状态可视化指示器
 */
@Composable
private fun VoiceStatusIndicator(
    voiceState: VoiceState,
    synthesisState: SynthesisState
) {
    Box(
        modifier = Modifier.size(60.dp),
        contentAlignment = Alignment.Center
    ) {
        when (voiceState) {
            VoiceState.IDLE -> {
                IdleIndicator()
            }
            VoiceState.LISTENING_WAKEUP -> {
                ListeningIndicator(isWakeup = true)
            }
            VoiceState.WAKEUP_DETECTED -> {
                WakeupDetectedIndicator()
            }
            VoiceState.LISTENING_SPEECH, VoiceState.RECORDING, VoiceState.ASR_START, VoiceState.RECOGNIZING -> {
                ListeningIndicator(isWakeup = false)
            }
            VoiceState.PROCESSING -> {
                ProcessingIndicator()
            }
            VoiceState.SPEAKING -> {
                SpeakingIndicator(synthesisState)
            }
            VoiceState.ERROR -> {
                ErrorIndicator()
            }
        }
    }
}

@Composable
private fun IdleIndicator() {
    Box(
        modifier = Modifier
            .size(40.dp)
            .background(
                color = Color.Gray.copy(alpha = 0.5f),
                shape = CircleShape
            ),
        contentAlignment = Alignment.Center
    ) {
        Text(
            text = "💤",
            fontSize = 20.sp
        )
    }
}

@Composable
private fun ListeningIndicator(isWakeup: Boolean) {
    val infiniteTransition = rememberInfiniteTransition(label = "listening")
    val scale by infiniteTransition.animateFloat(
        initialValue = 0.8f,
        targetValue = 1.2f,
        animationSpec = infiniteRepeatable(
            animation = tween(1000),
            repeatMode = RepeatMode.Reverse
        ),
        label = "scale"
    )
    
    Box(
        modifier = Modifier
            .size(40.dp)
            .scale(scale)
            .background(
                color = if (isWakeup) Color.Blue.copy(alpha = 0.7f) else Color.Green.copy(alpha = 0.7f),
                shape = CircleShape
            ),
        contentAlignment = Alignment.Center
    ) {
        Text(
            text = if (isWakeup) "👂" else "🎤",
            fontSize = 16.sp
        )
    }
}

@Composable
private fun WakeupDetectedIndicator() {
    val infiniteTransition = rememberInfiniteTransition(label = "wakeup")
    val scale by infiniteTransition.animateFloat(
        initialValue = 1.0f,
        targetValue = 1.3f,
        animationSpec = infiniteRepeatable(
            animation = tween(300),
            repeatMode = RepeatMode.Reverse
        ),
        label = "scale"
    )
    
    Box(
        modifier = Modifier
            .size(40.dp)
            .scale(scale)
            .background(
                color = Color.Yellow.copy(alpha = 0.8f),
                shape = CircleShape
            ),
        contentAlignment = Alignment.Center
    ) {
        Text(
            text = "⚡",
            fontSize = 20.sp
        )
    }
}

@Composable
private fun ProcessingIndicator() {
    val infiniteTransition = rememberInfiniteTransition(label = "processing")
    val rotation by infiniteTransition.animateFloat(
        initialValue = 0f,
        targetValue = 360f,
        animationSpec = infiniteRepeatable(
            animation = tween(2000, easing = LinearEasing)
        ),
        label = "rotation"
    )
    
    Box(
        modifier = Modifier
            .size(40.dp)
            .background(
                color = Color(0xFFFFA500).copy(alpha = 0.7f), // Orange
                shape = CircleShape
            ),
        contentAlignment = Alignment.Center
    ) {
        Text(
            text = "🤔",
            fontSize = 16.sp
        )
    }
}

@Composable
private fun SpeakingIndicator(synthesisState: SynthesisState) {
    val infiniteTransition = rememberInfiniteTransition(label = "speaking")
    
    // 音波动画
    val wavePhase by infiniteTransition.animateFloat(
        initialValue = 0f,
        targetValue = 2 * Math.PI.toFloat(),
        animationSpec = infiniteRepeatable(
            animation = tween(1000, easing = LinearEasing)
        ),
        label = "wave"
    )
    
    Box(
        modifier = Modifier.size(50.dp),
        contentAlignment = Alignment.Center
    ) {
        // 音波效果
        Canvas(modifier = Modifier.fillMaxSize()) {
            drawSoundWave(wavePhase)
        }
        
        // 中心图标
        Box(
            modifier = Modifier
                .size(30.dp)
                .background(
                    color = Color.Cyan.copy(alpha = 0.8f),
                    shape = CircleShape
                ),
            contentAlignment = Alignment.Center
        ) {
            Text(
                text = "🔊",
                fontSize = 14.sp
            )
        }
    }
}

private fun DrawScope.drawSoundWave(phase: Float) {
    val centerX = size.width / 2
    val centerY = size.height / 2
    val baseRadius = 15.dp.toPx()
    
    for (i in 1..3) {
        val radius = baseRadius + i * 8.dp.toPx() + 
                    5.dp.toPx() * sin(phase + i * 0.5f)
        
        drawCircle(
            color = Color.Cyan.copy(alpha = 0.3f / i),
            radius = radius,
            center = androidx.compose.ui.geometry.Offset(centerX, centerY),
            style = androidx.compose.ui.graphics.drawscope.Stroke(
                width = 2.dp.toPx(),
                cap = StrokeCap.Round
            )
        )
    }
}

@Composable
private fun ErrorIndicator() {
    Box(
        modifier = Modifier
            .size(40.dp)
            .background(
                color = Color.Red.copy(alpha = 0.7f),
                shape = CircleShape
            ),
        contentAlignment = Alignment.Center
    ) {
        Text(
            text = "❌",
            fontSize = 16.sp
        )
    }
}

/**
 * 获取状态文字描述
 */
private fun getStateText(voiceState: VoiceState, synthesisState: SynthesisState): String {
    return when (voiceState) {
        VoiceState.IDLE -> "语音助手就绪"
        VoiceState.LISTENING_WAKEUP -> "等待唤醒词..."
        VoiceState.WAKEUP_DETECTED -> "已唤醒！"
        VoiceState.LISTENING_SPEECH, VoiceState.RECORDING, VoiceState.ASR_START, VoiceState.RECOGNIZING -> "正在听您说话..."
        VoiceState.PROCESSING -> "正在思考中..."
        VoiceState.SPEAKING -> when (synthesisState) {
            SynthesisState.SYNTHESIZING -> "正在生成语音..."
            else -> "正在回答..."
        }
        VoiceState.ERROR -> "语音功能异常"
    }
}